"use strict";
//FYI: https://github.com/Tencent/puerts/blob/master/doc/unity/manual.md
Object.defineProperty(exports, "__esModule", { value: true });
const Utils_1 = require("./Utils");
var FairyEditor = CS.FairyEditor;
const GenCode_TS_1 = require("./GenCode_TS");
const File = CS.System.IO.File;
const Path = CS.System.IO.Path;
function getPackageAllDeps(handler) {
    const name = handler.fileName;
    let query = new FairyEditor.DependencyQuery();
    query.QueryDependencies(handler.pkg.items, FairyEditor.DependencyQuery.SeekLevel.ALL);
    let set = new Set();
    const list = query.resultList;
    for (let index = 0; index < list.Count; index++) {
        const item = list.get_Item(index);
        const pkg = item.item.owner;
        let targetName = pkg.publishSettings.fileName;
        if (!targetName || targetName.length <= 0) {
            targetName = handler.ToFilename(pkg.name);
        }
        // console.log('find depence : ', targetName);
        set.add(targetName);
    }
    if (set.has(name))
        set.delete(name);
    return set;
}
function setExportBundleInfo(handler, set, sameWithScript, includeScript) {
    const dir = handler.exportPath;
    const name = handler.fileName;
    // 设置Bundle信息，添加依赖
    const metaFile = dir + ".meta";
    if (!File.Exists(metaFile)) {
        console.error('无法为导出目录设置Bundle信息，请刷新Creator后重新导出！');
        return;
    }
    let deps = [];
    for (const dep of set) {
        deps.push(Utils_1.generatePackageResBundleName(dep));
    }
    if (!sameWithScript && includeScript) {
        deps.push(Utils_1.generatePackageScriptBundleName(name, false));
    }
    const json = File.ReadAllText(metaFile);
    let meta = JSON.parse(json);
    let userData = meta.userData;
    if (!userData)
        userData = {};
    userData.isBundle = true;
    userData.bundleName = Utils_1.generatePackageResBundleName(name);
    userData.auto_exclude = true;
    userData.dep_ext = deps.join(',');
    userData.priority = Math.max(userData.priority || 1, 5);
    meta.userData = userData;
    File.WriteAllText(metaFile, JSON.stringify(meta, null, 2));
}
function generateAutoLoad(handler, set, sameWithScript, includeScript) {
    const dir = handler.exportPath;
    const name = handler.fileName;
    const packageName = handler.ToFilename(handler.pkg.name);
    const allDeps = [];
    for (const dep of set) {
        allDeps.push(`'${dep}'`);
    }
    let head = `/** This is an automatically generated class by FairyGUI. Please do not modify it. **/

import { EDITOR } from 'cc/env';
import * as fgui from "db://fairygui-xforge/FairyGUI";
`;
    // 生成index.ts
    let context = `
fgui.UIPackageManager.bind('${packageName}', '${Utils_1.generatePackageResBundleName(name)}', '${name}', [${allDeps.join(',')}]);
if (!EDITOR) {
    fgui.UIPackageManager.load('${packageName}');
}`;
    if (sameWithScript && includeScript) {
        const bindFunc = Utils_1.generateBindAllFunctionName(handler);
        head += `import { ${bindFunc} } from "./binder";\n`;
        context += `\n\n${bindFunc}();\n`;
    }
    File.WriteAllText(Path.Combine(dir, "index.ts"), head + context);
}
function onPublish(handler) {
    const sameExport = handler.exportPath === handler.exportCodePath;
    const set = getPackageAllDeps(handler);
    generateAutoLoad(handler, set, sameExport, handler.genCode);
    setExportBundleInfo(handler, set, sameExport, handler.genCode);
    if (handler.genCode) {
        handler.genCode = false; //prevent default output
        console.log('Handling gen code in plugin');
        GenCode_TS_1.genCode(handler, sameExport); //do it myself
    }
}
exports.onPublish = onPublish;
function onDestroy() {
    //do cleanup here
}
exports.onDestroy = onDestroy;
